package com.example.demo.service.impl;

import com.example.demo.service.UserService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;


@Service
public class UserServiceImpl implements UserService {

    @Override
    @Async("asyncServiceExecutor")
    public Future<String> getById(Long id){
        try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName()+"异步处理完成！"+id);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(Thread.currentThread().getName()+"异步处理完成！"+id);
    }

    @Override
    public List<String> getById2(Long id) throws ExecutionException, InterruptedException {
        List<String> resultList = new ArrayList<>();
        // 创建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        List<Future> futureList = new ArrayList<>();
        // 多线程实现商品状态线程
        for ( int i = 0; i < 100; i++) {
            int finalI = i;
            Future<String> goodsStautsFuture = executorService.submit(
                    new Callable<String>() {
                        @Override
                        public String call() throws Exception {
                            Thread.sleep(1000);
                            System.out.println(Thread.currentThread().getName()+"异步处理完成！"+ finalI);
                            return Thread.currentThread().getName()+"异步处理完成！"+ finalI;
                        }
                    });
            futureList.add(goodsStautsFuture);
        }
        // 关闭线程池
        executorService.shutdown();
        for (Future f : futureList) {
            String msg=f.get().toString();
            resultList.add(msg);
        }
        return resultList;
    }

    @Override
    public String getById3(Long id){
        try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName()+"异步处理完成！"+id);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName()+"异步处理完成！"+id;
    }
}
